<template>
            <section>
              <!--工具条-->
              <el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
                <el-form :inline="true" :model="query">
                  <el-form-item>
                    <el-input v-model="query.keyword" placeholder="员工姓名"></el-input>
                  </el-form-item>
                  <el-form-item>
                    <el-button type="primary" v-on:click="getQueryEmployees">查询</el-button>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" @click="handleAdd">新增</el-button>
				</el-form-item>
			</el-form>
		</el-col>

		<!--列表-->
		<el-table :data="this.pageInfo.dataList" highlight-current-row v-loading="listLoading" @selection-change="selsChange" style="width: 100%;">
			<el-table-column type="selection" width="55">
			</el-table-column>
			<el-table-column type="index" width="60">
			</el-table-column>
			<el-table-column prop="username" label="员工名称" width="200" sortable>
			</el-table-column>
			<el-table-column prop="email" label="邮箱" width="250"  sortable>
			</el-table-column>
			<el-table-column prop="age" label="年龄" width="200" sortable>
			</el-table-column>
      <el-table-column prop="department.name" label="部门" min-width="200" sortable>
      </el-table-column>

			<el-table-column label="操作" width="150">
				<template scope="scope">
					<el-button size="small" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
					<el-button type="danger" size="small" @click="handleDel(scope.$index, scope.row)">删除</el-button>
          <el-button type="danger" size="small" @click="handleRole(scope.$index, scope.row)">授权角色</el-button>
				</template>
			</el-table-column>
		</el-table>

		<!--工具条-->
		<el-col :span="24" class="toolbar">
			<el-button type="danger" @click="batchRemove" :disabled="this.sels.length===0">批量删除</el-button>
<!--			<el-pagination layout="prev, pager, next" @current-change="handleCurrentChange" :page-size="this.query.pageSize" :total="this.pageInfo.total" style="float:right;">-->
<!--			</el-pagination>-->
      <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="this.query.currentPage"
          :page-sizes="[5,10,15,20]"
          :page-size="100"
          layout="total, sizes, prev, pager, next, jumper"
          :total="this.pageInfo.total"
          style="float:right">
      </el-pagination>

		</el-col>

		<!--新增/修改界面-->
		<el-dialog title="新增/修改" :visible.sync="saveFormVisible" :close-on-click-modal="false">
			<el-form :model="saveForm" label-width="80px" :rules="saveFormRules" ref="saveForm">
				<el-form-item label="员工名称" prop="username">
					<el-input v-model="saveForm.username" auto-complete="off"></el-input>
				</el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input type="textarea" v-model="saveForm.email"></el-input>
        </el-form-item>
        <el-form-item label="年龄" prop="age">
          <el-input type="textarea" v-model="saveForm.age"></el-input>
        </el-form-item>
        <el-form-item label="部门" prop="department">
          <el-select v-model="saveForm.department" clearable value-key="id" placeholder="请选择">
            <!--下拉选项
              :key=""  //唯一标识
              :label 选择之后展示到选择框中的值
              :value 选中之后绑定给模型层的值  如果要绑定对象给模型层 有一个大坑
                 必须要写  value-key="id"
            -->
            <el-option
                v-for="item in departments"
                :key="item.id"
                :label="item.name"
                :value="item">
              <span style="float: left">{{ item.name }}</span>
            </el-option>
          </el-select>
        </el-form-item>
<!--        <el-form-item label="部门">-->
<!--          <el-radio-group v-model="saveForm.department.name">-->
<!--        </el-form-item>-->
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button @click.native="saveFormVisible = false">取消</el-button>
				<el-button type="primary" @click.native="addSubmit" :loading="addLoading">提交</el-button>
			</div>
		</el-dialog>
    <!--授权角色界面-->
              <el-dialog title="角色授权" :visible.sync="saveRoleVisible" :close-on-click-modal="false">
                <el-form :model="employeeRole" label-width="80px"  ref="saveFrom">

                  <el-checkbox :indeterminate="isIndeterminate" v-model="checkAll" @change="handleCheckAllChange">全选</el-checkbox>
                  <div style="margin: 15px 0;"></div>
                  <el-checkbox-group v-model="checkedRoles" @change="handleCheckedCitiesChange">
                    <!--          <el-checkbox v-for="role in roleList" :label="role.id" :key="role.id" >{{role.name}}</el-checkbox>-->
                    <!-- 根据角色列表展示每个角色的信息 -->
                    <el-checkbox v-for="role in roleList" :label="role.id" :key="role.id" :checked="checkedRoles.includes(role.id)">{{ role.name }}</el-checkbox>
                  </el-checkbox-group>

                </el-form>
                <div slot="footer" class="dialog-footer">
                  <el-button @click.native="saveRoleVisible = false">取消</el-button>
                  <el-button type="primary" @click.native="saveRole" :loading="addLoading">授予角色</el-button>
                </div>
              </el-dialog>
	</section>
</template>

<script>
	import util from '../../common/js/util'
	//import NProgress from 'nprogress'
	// import { getUserListPage, removeUser, batchRemoveUser, editUser, addUser } from '../../api/api';
	export default {
		data() {
			return {
        checkAll: false,
        checkedRoles: [],
        roleList: [],			  //角色列表
        isIndeterminate: true,
        allChecked:[],  //全选时候的id

        // 弹出授权界面
        saveRoleVisible:false,

        employeeRole:{
          id:null,
          roleIds:[] // 用户的角色集合
        },


				query: {
					keyword: '',
          currentPage:1,
          pageSize:5
				},
        pageInfo:{
          dataList: [],
          total: 0,
        },
				page: 1,
				listLoading: false,
				sels: [],//列表选中列

				editFormVisible: false,//编辑界面是否显示
				editLoading: false,
				editFormRules: {
					username: [
						{ required: true, message: '请输入姓名', trigger: 'blur' }
					]
				},
				//编辑界面数据
				// editForm: {
				// 	id: 0,
				// 	name: '',
				// 	sex: -1,
				// 	age: 0,
				// 	birth: '',
				// 	addr: ''
				// },

				saveFormVisible: false,//新增界面是否显示
				addLoading: false,
				saveFormRules: {
					username: [
						{ required: true, message: '请输入员工名称', trigger: 'blur' }
					]
				},
				//新增界面数据
				saveForm: {
				  id:null,
          username:"",
          email:"",
          age:"",
          department:{
				    id:null,
            name:""
          }
				},
        departments:[],
			}
		},
		methods: {
      // 授权
      saveRole(){
        this.employeeRole.roleIds= this.checkedRoles
        // this.employeeRole.id=
        console.log("授权请求中的id"+this.employeeRole.id);
        console.log("授权方法中，employeeRole："+this.employeeRole.roleIds)

        this.$http.post("/employee/role",this.employeeRole)  //将选好的ids发送
            .then(result => {
              result = result.data;

              if(result.success){

                this.$message({ message: "保存成功",type: 'success'});
                this.saveRoleVisible=false
              }else{
                this.$message({ message: result.message,type: 'error'});
              }
            }).catch(result => {
          this.$message({ message: '/role/permission错误',type: 'error'});
        })
      },
      //获取这个员工已经有的角色列表
      getEmployeeRoles(id){
        this.$http.get("/employee/role/"+id)
            .then(result => {
              result = result.data;
              if(result.success){
                this.checkedRoles = result.resultObj;
                console.log("传入的id："+id)
                console.log("已经有的角色列表roleList:"+this.checkedRoles)
              }else{
                this.$message({ message: result.message,type: 'error'});
              }
            }).catch(result => {
          this.$message({ message: '获取角色列表错误',type: 'error'});
        })
      },
      //全选
      handleCheckAllChange(val) {
        this.checkedRoles = val ? this.allChecked : [];
        this.isIndeterminate = false;
      },
      handleCheckedCitiesChange(value) {
        let checkedCount = value.length;
        this.checkAll = checkedCount === this.roleList.length;
        this.isIndeterminate = checkedCount > 0 && checkedCount < this.roleList.length;
      },
      //显示授予角色界面
      handleRole: function (index, row) {
        this.saveRoleVisible = true;
        this.getRoleList()
        this.employeeRole.id= row.id
        this.getEmployeeRoles(this.employeeRole.id)//查询这个人已经有的权限
      },
      // 根据角色id获取其对应的角色id
      // 获取角色列表的方法
      getRoleList(){
        this.$http.get("/role")
            .then(result => {
              result = result.data;
              if(result.success){
                this.roleList = result.resultObj;
                console.log("roleList:"+this.roleList)
                for (let i = 0; i < this.roleList.length; i++) {
                  let p=this.roleList[i]
                  this.allChecked.push(p.id)
                }
              }else{
                this.$message({ message: result.message,type: 'error'});
              }
            }).catch(result => {
          this.$message({ message: '获取角色列表错误',type: 'error'});
        })
      },


      // handleCheckAllChange(val) {
      //   this.checkedRoles = val ? roleOptions : [];
      //   this.isIndeterminate = false;
      // },
      // handleCheckedRolesChange(value) {
      //   let checkedCount = value.length;
      //   this.checkAll = checkedCount === this.roles.length;
      //   this.isIndeterminate = checkedCount > 0 && checkedCount < this.roles.length;
      // },
      // getRoleById(id){
      //   this.$http.get("/employee/role/"+id)
      //       .then(result=>{
      //         console.log(result);
      //         result=result.data
      //         if (result.success){
      //           this.role.roleids=result.resultObj
      //         }else{
      //           this.$message({
      //             message: result.message,
      //             type: 'error'
      //           });
      //         }
      //       })
      //       .catch(result=>{
      //         this.$message({
      //           message: '系统错误',
      //           type: 'error'
      //         });
      //       })
      // },
      // getRole(){
      //   this.$http.get("/role")
      //       .then(result => {
      //         result = result.data
      //         if (result.success) {
      //           // this.roles=result.resultObj
      //           console.log("role-----:"+roles);
      //         } else {
      //         }
      //       })
      //       .catch(result => {
      //       })
      // },
      // handleRole(index,row){
      //   this.getRole()
      //   this.setPermissionVisible=true
      //   this.role.id=row.id
      //   // this.getRoleById(this.role.id)
      // },
      getDepartments(){
        this.$http.get("/department")
            .then(result => {
              result = result.data
              if (result.success) {
                this.departments=result.resultObj
              } else {
              }
            })
            .catch(result => {
            })
      } ,
		  handleSizeChange(val){

		    this.query.pageSize=val;
		    this.getEmployees()
      },
		  getQueryEmployees(){
		    this.query.currentPage=1
        this.getEmployees()
      },
      //分页显示转换为第1页
			handleCurrentChange(val) {
        console.log(val);
				this.query.currentPage = val;
        this.getEmployees()
      },
			//获取菜单列表
			getEmployees() {
				// let para = {
				// 	page: this.page,
				// 	name: this.filters.name
				// };
				this.listLoading = true;
				//NProgress.start();
        this.$http.put("/employee",this.query)
            .then(result=>{
              console.log(result);
              result=result.data
             if (result.success){
               this.$message({
                 message: '查询成功',
                 type: 'success'
               });
               this.listLoading = false;
               console.log(result);
               this.pageInfo=result.resultObj
               console.log(this.pageInfo.dataList)
             }else{
               this.$message({
                 message: '查询失败',
                 type: 'danger'
               });
             }
            })
            .catch(result=>{

            })
			},
			//删除
			handleDel: function (index, row) {
				this.$confirm('确认删除该记录吗?', '提示', {
					type: 'warning'
				}).then(() => {
					this.listLoading = true;
					//NProgress.start();
					let para = { id: row.id };
					this.$http.delete("/employee/"+row.id)
          .then(result=>{
            result=result.data
            if (result.success){
              this.$message({
                message: '删除成功',
                type: 'success'
              });
              this.listLoading = false;
              this.query.currentPage=1
              this.getEmployees()
            }else{
              this.$message({
                message: '删除失败',
                type: 'danger'
              });
            }
          })
				}).catch(() => {

				});
			},
			//显示编辑界面
			handleEdit: function (index, row) {
				this.saveFormVisible = true;
        this.getEmployees()
        this.getDepartments()
				this.saveForm = Object.assign({}, row)
        if (!row.department){
          this.saveForm.department={
            id:null,
            name:""
          }
        }
			},
			//显示新增界面
			handleAdd: function () {
				this.saveFormVisible = true;
				this.saveForm = {
          id:null,
          username:"",
          email:"",
          age:"",
          department:{
            id:null,
            name:""
          }
        }
        this.getEmployees()
        this.getDepartments()
			},
			//新增
			addSubmit: function () {
				this.$refs.saveForm.validate((valid) => {
					if (valid) {
						this.$confirm('确认提交吗？', '提示', {})
                .then(() => {
                  this.addLoading = true;
                  //NProgress.start();
                  let para = Object.assign({}, this.saveForm);
                  this.$http.post("/employee", para)
                      .then(result => {
                        result = result.data
                        if (result.success) {
                          this.$message({
                            message: '保存成功',
                            type: 'success'
                          });
                          this.addLoading = false;
                          this.saveFormVisible=false;
                          this.getEmployees()
                        } else {
                          this.$message({
                            message: '保存失败',
                            type: 'danger'
                          });
                        }
                      })
                      .catch(result => {
                        this.$message({message: "网络异常，请检查网络", type: "danger"})
                      })
                       }).catch({})
					}
				});
			},
			selsChange: function (sels) {
				this.sels = sels;
			},
			//批量删除
			batchRemove: function () {
				var ids = this.sels.map(item => item.id)
				this.$confirm('确认删除选中记录吗？', '提示', {
					type: 'warning'
				}).then(() => {
          this.listLoading = true;
          //NProgress.start();
          this.$http.patch("/employee",ids)
              .then(result => {
                result = result.data
                if (result.success) {
                  this.$message({
                    message: '批量删除成功',
                    type: 'success'
                  });
                  this.listLoading = false;
                  this.query.currentPage = 1
                  this.getEmployees()
                } else {
                  this.$message({
                    message: '批量删除失败',
                    type: 'danger'
                  });
                }
              })
              .catch(result=>{

                })
              })
              .catch(() => {

              });
        }
		},
		mounted() {
			this.getEmployees();
		}
	}

</script>

<style scoped>

</style>